package com.jz.community.moduleshoppingguide.home.ui.adapter;

import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

import com.jz.community.basecomm.base.BaseMvpFragment;
import com.jz.community.moduleshoppingguide.home.bean.HotSaleShowBean;
import com.jz.community.moduleshoppingguide.home.ui.fragment.BestSellersFragment;

import java.util.ArrayList;
import java.util.List;

public class BestSellersPageAdapter extends FragmentStatePagerAdapter {


    private List<HotSaleShowBean.EmbeddedBean.ContentBean> list;
    private FragmentManager fm;
    private int message;

    public BestSellersPageAdapter(FragmentManager fm, List<HotSaleShowBean.EmbeddedBean.ContentBean> list, int message) {
        super(fm);
        this.fm = fm;
        if (list != null && list.size() > 0) {
            this.list = list;
        } else {
            this.list = new ArrayList<>();
        }
        this.message = message;
    }

    @Override
    public BaseMvpFragment getItem(int position) {
        return BestSellersFragment.newInstance(list.get(position).getChunnelShowId() + "", message);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return list.get(position).getChunnelShowName();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        //拿到缓存的fragment，如果没有缓存的，就新建一个，新建发生在fragment的第一次初始化时
        BaseMvpFragment f = (BaseMvpFragment) super.instantiateItem(container, position);
        String fragmentTag = f.getTag();
        if (f != getItem(position)) {
            //如果是新建的fragment，f 就和getItem(position)是同一个fragment，否则进入下面
            FragmentTransaction ft = fm.beginTransaction();
            //移除旧的fragment
            ft.remove(f);
            //换成新的fragment
            f = getItem(position);
            //添加新fragment时必须用前面获得的tag
            ft.add(container.getId(), f, fragmentTag);
            ft.attach(f);
            ft.commitAllowingStateLoss();
        }
        return f;
    }
}
